﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Framework.Poco;
using Shell.DomainDot;
using Framework.Domain;

namespace Framework.Mvc
{
    public class AgencyModelBinder : DefaultModelBinder, IModelBinder
    {
        static AgencyModelBinder()
        {
            AgencyModelBinderModelName = "currentAgency";
        }

        public static string AgencyModelBinderModelName;

        public IEnumerable<Agency> StoredAgencies()
        {
            IDomainDotFactory factory = DomainDotFactory.Factory;
            var context = factory.Create<GlobalContext>();
            return context.GetAllAgencies();
        }

        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelName.Equals(AgencyModelBinderModelName, StringComparison.CurrentCulture))
            {
                var anencyName = controllerContext.HttpContext.Session["agencyName"] as string;
                if (!String.IsNullOrEmpty(anencyName))
                {
                    return this.StoredAgencies().SingleOrDefault(a => a.Name.Equals(anencyName, StringComparison.CurrentCultureIgnoreCase));
                }
                else
                {
                    var identity = controllerContext.HttpContext.User.Identity;
                    if (identity.IsAuthenticated)
                    {
                        return this.StoredAgencies().SingleOrDefault(a => a.Name.Equals(identity.Name, StringComparison.CurrentCultureIgnoreCase));
                    }
                    else
                    {
                        return null;
                    }
                }
            }
            return base.BindModel(controllerContext, bindingContext);
        }
    }
}